package com.qd.panda.service.func;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.panda.mapper.func.ChannelUserMapper;
import com.qd.panda.model.Channel;
import com.qd.panda.model.ChannelUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 渠道发展用户
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ChannelUserService extends BaseService<ChannelUserMapper, ChannelUser> {

    private final ChannelService channelService;

    @Transactional(rollbackFor = Exception.class)
    public void bind(ChannelUser channelUser) {
        Channel channel = channelService.getById(channelUser.getChannelCode());
        if (null != channel && channel.getEnable().equals(ConstantDto.SF1)) {
            super.save(channelUser);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void unbind(String userId) {
        QueryWrapper<ChannelUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("bind_state", PandaConstant.CHANNEL_USER_BIND_STATE_0);
        List<ChannelUser> channelUsers = super.baseMapper.selectList(queryWrapper);
        queryWrapper.clear();

        if (!channelUsers.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            for (ChannelUser channelUser : channelUsers) {
                channelUser.setBindTime(now);
                channelUser.setBindState(PandaConstant.CHANNEL_USER_BIND_STATE_1);
            }
            super.updateBatchById(channelUsers);
            channelUsers.clear();
        }
    }

    @Transactional(readOnly = true)
    public boolean isExistsByChannelCode(String channelCode) {
        QueryWrapper<ChannelUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("channel_code", channelCode);
        boolean exists = super.getBaseMapper().exists(queryWrapper);
        queryWrapper.clear();
        return exists;
    }
}